<?php
namespace App\Http\Controllers\Partner;
use App\Http\Controllers\ApiBaseController;
use Illuminate\Http\Request;
use App\Models\PartnerModels\Partner;
use App\Models\OrderModels\Order;
use App\Models\PartnerModels\RealName;
use App\Models\ExpModels\Exp;
use App\Models\PartnerModels\Consulting;
use App\Models\PartnerModels\Photo;
use App\Components\QiniuTools;
use App\Components\Tools;
use App\Models\TalentModels\Talent;
class PartnerAjaxController extends ApiBaseController{
	public function __construct(Request $request) {
		parent::__construct($request);
	}
	//爆店码视频审核页面数据拉取
    function getViedeoData(Request $request){
        $soExp=new Exp();
        $result = $soExp-> getVideoData($this->params);
        echo json_encode($result);
    }
    //爆店码视频审核保存操作
    function expVideoSave(Request $request){
        $data=$this->params;
        //  print_r($data);exit();
        $soExp=new Exp();
        $kid=isset($data['kid']) && intval($data['kid'])>0 ? intval($data['kid']) : $this->returnJson(1,"数据错误");
        $status=isset($data['status']) ? intval($data['status']) : $this->returnJson(1,"数据错误");
        $remark=isset($data['remark']) ? $data['remark'] : '';
        //审核不通过
        if($status==-1){
            $data=array(
                'audit'=>-1,
                'updateTime'=>date('Y-m-d H:i:s',time()),
                'remark'=>$remark,
                'operator'=>session('user')[0]['admin_name'],
            );
            $re=$soExp->updateAll($kid,$data);
            $re ? $this->returnJson(0,'操作成功') : $this->returnJson(1,'操作失败');
        }else{
            $data=array(
                'audit'=>1,
                'updateTime'=>date('Y-m-d H:i:s',time()),
                'operator'=>session('user')[0]['admin_name'],
            );
            $re=$soExp->updateAll($kid,$data);
            $re ? $this->returnJson(0,'操作成功') : $this->returnJson(1,'操作失败');
        }

    }
    //同城拓客视频页面数据拉取
    public function getViedeoInfo(Request $request){
        $soExp=new Exp();
        $result = $soExp->getExpDataAll($this->params);
    //    print_r($result);exit();
        echo json_encode($result);
    }
	//实名认证数据拉取·
    public function getRealInfo(Request $reques){

        $soRealName= new RealName();
        $result=$soRealName->getPageData($this->params);
        echo json_encode($result);
    }
    //获取达人视频数据
    public function getTalentVideo(){
     //   print_r(1111);exit();
        $Talent=new Talent();
        $result=$Talent->getTalentData($this->params);
        exit(json_encode($result));
    }

    //审核列表数据拉取
    function searchAll(){
        $soRealName= new RealName();
        $result=$soRealName->getPageDataAll($this->params);
        echo json_encode($result);
    }
//合伙人数据
	public function dataList(){
		$oPartner = new Partner();
		$result = $oPartner->getPageData($this->params);
		echo json_encode($result);
	}
    
	//拉取合伙人详情
	function viewInfo(){
		$oPartner = new Partner();
		$re=$oPartner->viewInfo($this->params['kid']);
		if($re){
			$this->returnJson(0,$re);
		}
		$this->returnJson(1,"数据错误");
	}
	//拉取合伙人旗下的会员号
    public function countVipsInfo(){
        $oPartner = new Partner();
        $re=$oPartner->getPartnerVipData($this->params);
        if($re){
            $this->returnJson(0,$re);
        }
        $this->returnJson(1,"数据错误");
    }
	//8.31实名审核操作
    function realSave(Request $request){
	    $data=$this->params;
	//  print_r($data);exit();
        $soRealName= new RealName();

        $kid=isset($data['kid']) && intval($data['kid'])>0 ? intval($data['kid']) : $this->returnJson(1,"数据错误");
        $status=isset($data['status']) ? intval($data['status']) : $this->returnJson(1,"数据错误");
        $remark=isset($data['remark']) ? $data['remark'] : '';
        $pid=$soRealName->getpid($kid);
        //审核不通过
        if($status==-1){
            $data=array(
                'status'=>-1,
                'update_time'=>date('Y-m-d H:i:s',time()),
                'remark'=>$remark,
                'operator'=>session('user')[0]['admin_name'],
            );
            $re=$soRealName->updateAll($kid,$data);
            $date=array(
                'authentication'=>-1,
                'update_time'=>date('Y-m-d H:i:s',time()),
            );
            $soRealName->updatepattnerAll($pid,$date);
            $re ? $this->returnJson(0,'操作成功') : $this->returnJson(1,'操作失败');
        }else{
            $data=array(
                'status'=>2,
                'update_time'=>date('Y-m-d H:i:s',time()),
                'operator'=>session('user')[0]['admin_name'],
            );
            $re=$soRealName->updateAll($kid,$data);
            $date=array(
                'authentication'=>2,
                'update_time'=>date('Y-m-d H:i:s',time()),
            );
            $soRealName->updatepattnerAll($pid,$date);
            $re ? $this->returnJson(0,'操作成功') : $this->returnJson(1,'操作失败');
        }

    }
    //官网咨询数据获取
    function consultingData(Request $request){
        $data=$this->params;
        $soConsulting=new Consulting();
        $re=$soConsulting->getPageData($data);
        return isset($re)?$re:$this->returnJson(1,'暂无数据');
    }
    //修改
    function consultingChange(Request $request){

        $time=date('Y-m-d H:i:s',time());
        if(isset($this->params['kid']) && intval($this->params['kid']) > 0 && isset($this->params['status'])){
            $soConsulting=new Consulting();
            if($soConsulting->db_update('',$this->params['kid'],['status'=>$this->params['status'],'update_time'=>$time])){
                $this->data = true;
            }else{
                $this->code = 1;
                $this->msg = '操作失败1';
            }
        }else{
            $this->code = 1;
            $this->msg = '缺少数据1';
        }
        $this->boot();
    }
    //获取首页轮播图数据
    function photoData(Request $request){
        $data=$this->params;
        $soPhoto= new Photo();
        //获取数据
        $re=$soPhoto->getPageData($data);
        return isset($re)?$re:$this->returnJson(1,'暂无数据');
    }
    //修改轮播图状态页面
    function photoChange(Request $request){

        $time=date('Y-m-d H:i:s',time());
        if(isset($this->params['kid']) && intval($this->params['kid']) > 0 && isset($this->params['status'])){
            $soPhoto= new Photo();
            if($soPhoto->db_update('',$this->params['kid'],['status'=>$this->params['status'],'update_time'=>$time])){
                $this->data = true;
            }else{
                $this->code = 1;
                $this->msg = '操作失败1';
            }
        }else{
            $this->code = 1;
            $this->msg = '缺少数据1';
        }
        $this->boot();
    }
    //上传方法（七牛云）
    // 再这判断成功之后上传数据入库(实名认证)
    function qiniuUploadReal()
    {  // echo "<pre/>";print_r($_FILES);
        $soQiniuTools=new QiniuTools();
        $soPhoto=new Photo();
        $data=$this->params;
        $url=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
        $fileImgArr = isset($_FILES['fileImg']['name']) && !empty($_FILES['fileImg']['name']) ? $_FILES['fileImg'] : $this->returnJson('1', '请上传封面');
        if ($fileImgArr) {
            $tpurl=$soQiniuTools->upImg($fileImgArr,$path="data/lbt/img");
        }
        $date=array(
            'photo_url'=>$tpurl,
            'content'=>isset($this->params['content']) ? $this->params['content']:'',
            'status'=>1,
            'herf_url'=>isset($this->params['herfurl']) ? $this->params['herfurl']:'',
            'create_time'=>date('Y-m-d H:i:s',time()),
            'update_time'=>date('Y-m-d H:i:s',time()),
        );
      // print_r($date);exit();
        $soPhoto->db_insert($date);
        $this->returnJson(0,'上传成功');
        }



  /**
    * 操作状态
    * 开启/关闭
    */
	public function deleteData(){
	    $this->params['update_time']=date('Y-m-d H:i:s',time());
		if(isset($this->params['id']) && intval($this->params['id']) > 0 && isset($this->params['status'])){
			$oPartner = new Partner();
			if($oPartner->db_update('',$this->params['id'],['status'=>$this->params['status'],'update_time'=>$this->params['update_time']])){
				$this->data = true;
			}else{
				$this->code = 1;
				$this->msg = '操作失败';
			}
		}else{
			$this->code = 1;
			$this->msg = '缺少数据';
		}
		$this->boot();
	}

	//添加合伙人操作
	public function createSave(){
		$params = $this->params;
		// echo "<pre>";print_r($params);exit();
		$this->checkParams(0,$params);
		$oPartner = new Partner();
	//	print_r(session('user'));exit();
		$discount=isset($params['discount']) ? $params['discount'] : 0;
		$balance=$discount>0 ? ( $discount*$params['first_price'] ) : $params['first_price'];//折后金额
		$data=array(
            'createname'=>session('user')[0]['admin_name'],
			'fid'=>session('user')[0]['admin_id'],
			'type'=>1,
			'user_name'=>trim($params['user_name']),
			'pwd'=>\App\Components\Tools::passwordEncryption(trim($params['pwd'])),
			'city'=>htmlspecialchars($params['city'],ENT_QUOTES),
			'company'=>htmlspecialchars($params['company'],ENT_QUOTES),
			'address'=>htmlspecialchars($params['address'],ENT_QUOTES),
			'name'=>htmlspecialchars($params['name'],ENT_QUOTES),
			'mobile'=>$params['mobile'],
			'gender'=>intval($params['gender'])>0 ? intval($params['gender']) : 1,
			'wechat'=>htmlspecialchars($params['wechat'],ENT_QUOTES),
			'email'=>htmlspecialchars($params['email'],ENT_QUOTES),
			'discount'=>$discount,
			'balance'=>$balance,
			'first_price'=>intval($params['first_price']),
			'create_time'=>date('Y-m-d H:i:s',time()),
			'update_time'=>date('Y-m-d H:i:s',time()),
		);
		$kid=$oPartner->db_insertGetId($data);
		if($kid){
			//金额变动记录
			$priceData=[
				'partner_id'=>$kid,
				'old_price'=>0,
				'new_price'=>$balance,
				'num_price'=>$balance,
				'create_id'=>session('user')[0]['admin_id'],
				'create_type'=>0,
				'create_time'=>date('Y-m-d H:i:s',time()),
				'price_type'=>0,
				'content'=>"合伙人开户，账号：({$params['user_name']})",
			];
			$oPartner->inPriceChange($priceData);
			
			//生成订单信息 start
			$orderArray=array(
				'ca_number'=>intval($params['pay_type'])==4 ? (isset($params['ca_number']) ? htmlspecialchars($params['ca_number'],ENT_QUOTES) : '') : '',
				'partner_id'=>$kid,
				'type'=>3,
				'pay_type'=>intval($params['pay_type']),
				'order_no'=>str_shuffle(date('YmdHis',time())).time(),
				'remark'=>isset($params['remark']) ? htmlspecialchars($params['remark'],ENT_QUOTES) : '',
				'discount'=>$discount,
				'create_time'=>date('Y-m-d H:i:s',time()),
				'price'=>intval($params['first_price']),
				'status'=>200,
				'title'=>"合伙人开户",
			);
			$this->orderSave(0,$orderArray);
			// end
			$this->returnJson(0,'添加成功',URL('admin/partner/list'));
		}
		$this->returnJson(1,'添加失败');
	}
	
	//修改合伙人操作
	public function editSave(){
		$params = $this->params;
		$this->checkParams(1,$params);
		//查询该合伙人是否存在
		$oPartner = new Partner();
		$partnerData = $oPartner->selectParh($params['kid']);
		// echo "<pre>";print_r($partnerData);exit();
		!$partnerData ? $this->returnJson(1,'合伙人不存在') : '';
		
		$pwd=$partnerData['pwd'];
		if( trim($params['pwd']) ){
			$pwd=\App\Components\Tools::passwordEncryption(trim($params['pwd']));
		}
		
		$discount=isset($params['discount']) ? $params['discount'] : 0;
		$balance=$discount>0 ? ( $discount*$params['first_price'] ) : $params['first_price'];//折后金额
		$data=array(
			'pwd'=>$pwd,
			'city'=>htmlspecialchars($params['city'],ENT_QUOTES),
			'company'=>htmlspecialchars($params['company'],ENT_QUOTES),
			'address'=>htmlspecialchars($params['address'],ENT_QUOTES),
			'name'=>htmlspecialchars($params['name'],ENT_QUOTES),
			'mobile'=>$params['mobile'],
			'gender'=>intval($params['gender'])>0 ? intval($params['gender']) : 1,
			'wechat'=>htmlspecialchars($params['wechat'],ENT_QUOTES),
			'email'=>htmlspecialchars($params['email'],ENT_QUOTES),
			'update_time'=>date('Y-m-d H:i:s',time())
		);
		if( $discount!=$partnerData['discount'] || $params['first_price']!=$partnerData['first_price'] ){
			$data['discount']=$discount;
			$data['balance']=$balance;
			$data['first_price']=$params['first_price'];
		}
		$upkid=$oPartner->db_update('',$params['kid'],$data);
		if($upkid){
			if( $discount!=$partnerData['discount'] || $params['first_price']!=$partnerData['first_price'] ){
				//金额变动记录
				$priceData=[
					'partner_id'=>$params['kid'],
					'old_price'=>$partnerData['balance'],
					'new_price'=>$balance,
					'num_price'=>0,
					'create_id'=>session('user')[0]['admin_id'],
					'create_type'=>0,
					'create_time'=>date('Y-m-d H:i:s',time()),
					'price_type'=>2,
					'content'=>"合伙人修改，账号：({$partnerData['user_name']})",
				];
				$oPartner->inPriceChange($priceData);
				
				//生成订单信息 start
				$orderArray=array(
					'ca_number'=>isset($params['ca_number']) ? htmlspecialchars($params['ca_number'],ENT_QUOTES) : '',
					'pay_type'=>intval($params['pay_type']),
					'remark'=>isset($params['remark']) ? htmlspecialchars($params['remark'],ENT_QUOTES) : '',
					'discount'=>$discount,
					'create_time'=>date('Y-m-d H:i:s',time()),
					'price'=>$params['first_price'],
				);
				$this->orderSave($params['kid'],$orderArray);
			}
			$this->returnJson(0,'修改成功',URL('admin/partner/list'));
		}
		$this->returnJson(1,'修改失败');
	}
	
	//添加修改合伙人会员 操作相应的订单信息
	public function orderSave($partner_id,$data){
		$order=new Order();
		if($partner_id){
			$where="partner_id=$partner_id and type=3";
			$order->updateOrder($where,$data);
		}else{
			$order->db_insert($data);
		}
	}
	
	//判断 添加修改的 参数是否完整   type 0(添加) 1(修改)   params 数据集合
	public function checkParams($type=0,$params){
		$oPartner = new Partner();
		if(!is_array($params)){
			$this->returnJson(1,'数据错误');
		}
		if(!$type){
			$checkUname=\App\Components\Tools::checkUname($params['user_name']);
			!$checkUname ? $this->returnJson(1,'请正确输入5-11位 字母、数字、下划线 的用户名') : '';
			$check_uname=$oPartner->checkUname($params['user_name']);
			$check_uname ? $this->returnJson(1,'该用户名已存在') : '';
		}
		
		$checkUpwd=\App\Components\Tools::checkUpwd($params['pwd']);
		if( (!$type && !$checkUpwd) || ($type && $params['pwd'] && !$checkUpwd) ){
			$this->returnJson(1,'请正确输入6-16位字母、数字、下划线的 密码');
		}
		if(!isset($params['city']) || empty($params['city'])){
			$this->returnJson(1,'请输入所在地');
		}
		if(!isset($params['company']) || empty($params['company'])){
			$this->returnJson(1,'请输入机构');
		}
		if(!isset($params['address']) || empty($params['address'])){
			$this->returnJson(1,'请输入具体地址');
		}
		if(!isset($params['name']) || empty($params['name'])){
			$this->returnJson(1,'请输入联系人');
		}
		$checkUmobile=\App\Components\Tools::checkUmobile($params['mobile']);
		if(!$checkUmobile){
			$this->returnJson(1,'请正确输入手机号');
		}
		$checkDiscountTwo=\App\Components\Tools::checkDiscountTwo($params['discount']);
		if(!$checkDiscountTwo){
			$this->returnJson(1,'开户倍数有误！倍数只能是小于等于100的数值，最多一位小数');
		}
		if(!preg_match("/^[1-9]{1}[0-9]{0,}/",$params['first_price'])){
			$this->returnJson(1,'开户金额有误！请输入不以0开头的整数');
		}
		/*if(!isset($params['start_date']) || empty($params['start_date'])){
			$this->returnJson(1,'请选择合作开始日期');
		}
		if(!isset($params['end_date']) || empty($params['end_date'])){
			$this->returnJson(1,'请选择合作截止日期');
		}
		if((strtotime($params['end_date'])-strtotime($params['start_date']))/24/3600<=0){
			$this->returnJson(1,'合作截止日期不能小于合作开始日期');
		}*/
		if(!isset($params['pay_type']) || intval($params['pay_type'])<1){
			$this->returnJson(1,'请选择支付方式');
		}
		if($params['pay_type']==4 && (!isset($params['ca_number']) || empty($params['ca_number'])) ){
			$this->returnJson(1,'请输入对公账户号');
		}
	}
	
	//合伙人充值
	function saveCharging(){
		// echo "<pre/>";print_r($this->params);exit;
		$partner_discount=\App\Components\Tools::getOneconfig('/config/config.json',array('basics','partner_discount'));
		$partner_id=isset($this->params['kid']) ? intval($this->params['kid']) : $this->returnJson(1,'参数错误');
		$type=isset($this->params['type']) ? intval($this->params['type']) : 0;
		$price=isset($this->params['price']) ? $this->params['price'] : 0;
		$actualPrice=isset($this->params['actualPrice']) ? $this->params['actualPrice'] : 0;
		
		$order=new Order();
		$oPartner = new Partner();
		$partnerData = $oPartner->selectParh($partner_id);
		!$partnerData ? $this->returnJson(1,'合伙人不存在') : '';
		
		if($type==1){
			if(!preg_match("/^[1-9]{1}[0-9]{0,}00$/",$price)){
				$this->returnJson(1,'充值金额：必须是100的倍数');
			}
			
			$num_price=$partner_discount*$price; //充值的实际金额
			$new_price=$num_price+$partnerData['balance']; //充值后的余额
			$re=$oPartner->db_update('',$partnerData['id'],['balance'=>$new_price]); // 改变账户余额
			if($re){
				//金额变动记录
				$priceData=[
					'partner_id'=>$partner_id,
					'old_price'=>$partnerData['balance'],
					'new_price'=>$new_price,
					'num_price'=>$num_price,
					'create_id'=>session('user')[0]['admin_id'],
					'create_type'=>0,
					'create_time'=>date('Y-m-d H:i:s',time()),
					'price_type'=>0,
					'content'=>"账户充值",
				];
				$oPartner->inPriceChange($priceData);
				
				//生成订单信息 start
				$orderData=[
					'partner_id'=>$partner_id,
					'type'=>1,
					'pay_type'=>4,
					'order_no'=>str_shuffle(date('YmdHis',time())).time(),
					'discount'=>$partner_discount,
					'create_time'=>date('Y-m-d H:i:s',time()),
					'price'=>$price,
					'status'=>200,
					'title'=>"账户充值",
				];
				$order->db_insert($orderData);
				
				//充值记录
				$chargingData=[
					'pid'=>$partner_id,
					'price'=>$price,
					'actualPrice'=>$num_price,
					'discount'=>$partner_discount,
					'create_id'=>session('user')[0]['admin_id'],
					'created'=>date('Y-m-d H:i:s',time()),
				];
				$oPartner->inCharging($chargingData);
				$this->returnJson(0,'充值成功');
			}
		}elseif($type==2){
			if(!preg_match("/^[1-9]{1}[0-9]{0,}00$/",$price)){
				$this->returnJson(1,'充值金额：必须是100的倍数');
			}
			if(!preg_match("/^[1-9]{1}[0-9]{0,}00$/",$actualPrice)){
				$this->returnJson(1,'实际金额：必须是100的倍数');
			}
			
			$new_price=$actualPrice+$partnerData['balance']; //充值后的余额
			$re=$oPartner->db_update('',$partnerData['id'],['balance'=>$new_price]); // 改变账户余额
			if($re){
				//金额变动记录
				$priceData=[
					'partner_id'=>$partner_id,
					'old_price'=>$partnerData['balance'],
					'new_price'=>$new_price,
					'num_price'=>$actualPrice,
					'create_id'=>session('user')[0]['admin_id'],
					'create_type'=>0,
					'create_time'=>date('Y-m-d H:i:s',time()),
					'price_type'=>0,
					'content'=>"账户充值",
				];
				$oPartner->inPriceChange($priceData);
				
				//生成订单信息 start
				$orderData=[
					'partner_id'=>$partner_id,
					'type'=>1,
					'pay_type'=>4,
					'order_no'=>str_shuffle(date('YmdHis',time())).time(),
					'discount'=>0,
					'create_time'=>date('Y-m-d H:i:s',time()),
					'price'=>$price,
					'status'=>200,
					'title'=>"账户充值",
				];
				$order->db_insert($orderData);
				
				//充值记录
				$chargingData=[
					'pid'=>$partner_id,
					'price'=>$price,
					'actualPrice'=>$actualPrice,
					'discount'=>0,
					'create_id'=>session('user')[0]['admin_id'],
					'created'=>date('Y-m-d H:i:s',time()),
				];
				$oPartner->inCharging($chargingData);
				$this->returnJson(0,'充值成功');
			}
		}elseif($type==3){
			$new_price=$partnerData['balance']-$price; //扣费后的余额
			$re=$oPartner->db_update('',$partnerData['id'],['balance'=>$new_price]); // 改变账户余额
			if($re){
				//金额变动记录
				$priceData=[
					'partner_id'=>$partner_id,
					'old_price'=>$partnerData['balance'],
					'new_price'=>$new_price,
					'num_price'=>$price,
					'create_id'=>session('user')[0]['admin_id'],
					'create_type'=>0,
					'create_time'=>date('Y-m-d H:i:s',time()),
					'price_type'=>1,
					'content'=>"账户扣费",
				];
				$oPartner->inPriceChange($priceData);
				
				//充值记录
				$chargingData=[
					'pid'=>$partner_id,
					'price'=>$price,
					'actualPrice'=>$price,
					'discount'=>0,
					'type'=>1,
					'create_id'=>session('user')[0]['admin_id'],
					'created'=>date('Y-m-d H:i:s',time()),
				];
				$oPartner->inCharging($chargingData);
				$this->returnJson(0,'扣费成功');
			}
		}
		$this->returnJson(1,'参数错误');
	}
}